class EventBus{
    constructor(max) {
        this.events = {}
        this.maxListener = max || Infinity
    }

    on(event, cb){
        // 先要声明一个数组， 如果当前事件不存在的话， 初始化一个数组
        if(!this.events[event]) {
            this.events[event] = []
        }
        if(this.maxListener !== Infinity && this.events[event].length > this.maxListener) {
            console.log(`事件${event}超过最大监听数`)
            return this;
        }
        this.events[event].push(cb)
        return this;
    }
    once(event, cb){
        const fn = (...args) => {
            this.off(event, fn)
            cb.call(this, args)
        }
        this.on(event, fn)

        return this;
    }
    emit(event, ...args){
        const cbs = this.events[event]
        if(!cbs) {
            console.log('没有该事件')
            return this;
        }
        cbs.forEach(cb => cb.call(this, args))
        return  this;
    }
    off(event, cb){
        // 一个事件上可以挂载好多的函数， 如果没有函数， 那么就删除该事件上的所有函数
        if(!cb) {
            this.events[event] = null
        }else{
            // 删除事件上指定的cb
            this.events[event] = this.events[event].filter(item => item !== cb)
        }
        return this;
    }
}

const events = new EventBus(2);
events.on('sum', (a, b) => {console.log(a + b)})
events.on('sum', (a, b) => {console.log(a + b + 1)})
events.on('sum', (a, b) => {console.log(a + b + 2)})
events.emit('sum', 1, 2)
